<template>
  <div class="nav-header">
    <ElTabs
      v-show="routers.length"
      v-model="activeName"
      type="border-card"
      :closable="routers.length > 1"
      @tab-change="handleChange"
      @tab-remove="handleRemove"
      :class="globalConfig.tabsStyle"
    >
      <ElTabPane
        v-for="(item, index) in routers"
        :key="index"
        :name="item.name"
      >
        <template #label>
          <template v-if="item.icon && item.icon.startsWith('icon')">
            <ElIcon class="iconfont" :class="item.icon" />
          </template>
          <template v-else-if="item.icon">
            <ElIcon>
              <component :is="item.icon" />
            </ElIcon>
          </template>
          <span class="tab_label">{{ item.label }}</span>
        </template>
      </ElTabPane>
    </ElTabs>
    <div class="actions">
      <ElDropdown class="action_item" trigger="click" @command="handleCommand">
        <ElButton icon="ArrowDownBold" link></ElButton>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem command="close" :disabled="disabledAction">
              <ElIcon><Close /></ElIcon>
              <span>{{ $t("navHeader.Close") }}</span>
            </ElDropdownItem>
            <ElDropdownItem command="open">
              <ElIcon class="iconfont icon-fenxiang"></ElIcon>
              <span>{{ $t("navHeader.OpenNewWindow") }}</span>
            </ElDropdownItem>
            <ElDropdownItem
              command="closeLeft"
              divided
              :disabled="disabledAction"
            >
              <ElIcon class="iconfont icon-guanbizuoce"></ElIcon>
              <span>{{ $t("navHeader.CloseLeft") }}</span>
            </ElDropdownItem>
            <ElDropdownItem command="closeRight" :disabled="disabledAction">
              <ElIcon class="iconfont icon-guanbiyouce"></ElIcon>
              <span>{{ $t("navHeader.CloseRight") }}</span>
            </ElDropdownItem>
            <ElDropdownItem
              command="closeOther"
              divided
              :disabled="disabledAction"
            >
              <ElIcon class="iconfont icon-guanbiqita"></ElIcon>
              <span>{{ $t("navHeader.CloseOther") }}</span>
            </ElDropdownItem>
            <ElDropdownItem command="closeAll" :disabled="disabledAction">
              <ElIcon class="iconfont icon-close-all"></ElIcon>
              <span>{{ $t("navHeader.CloseAll") }}</span>
            </ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
    </div>
  </div>
</template>

<script setup>
import { computed, inject, ref, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import eventEmitter from "@/utils/eventEmitter";
import { dfsArray, merge } from "@/utils";
import { useRouteState } from "@/store";
import { useNavigation } from "./useNavigation";
const router = useRouter();
const route = useRoute();
const activeName = ref("");
const routeState = useRouteState();
const disabledAction = computed(() => {
  return routers.value.length === 1;
});
const globalConfig = inject("globalConfig");
const { push } = useNavigation();
// TODO: 添加缓存功能 以及添加hooks？{pushRouter,removeRouter,updateRouter}
/**
 * {
 *  path:"",
 *  name:"",
 *  label:"",
 *  icon:"",
 *  query:{}
 * }
 */
const routers = ref([]);
// 添加
eventEmitter.on("nav:add", (item, isAddRouter) => {
  routers.value.push(item);
  // 自动添加路由
  if (isAddRouter) {
    router.push({
      path: item.path,
      query: item.query || {},
    });
  }
});
// 修改
eventEmitter.on("nav:update", (path, object, isUpdateRouter) => {
  const p = typeof path === "object" ? path.path : path;
  const routerInfo = routers.value.find((v) => v.path === p);
  merge(routerInfo, typeof path === "object" ? path : object);
  // 自动更新路由
  if (isUpdateRouter) {
    router.replace({
      path: routerInfo.path,
      query: routerInfo.query || {},
    });
  }
});
function handleChange(name) {
  const routerInfo = routers.value.find((item) => item.name === name);
  if (!routerInfo) {
    return;
  }
  push({
    path: routerInfo.path,
    query: routerInfo.query || {},
  });
  eventEmitter.emit("menu:update", routerInfo.path);
}

function handleRemove(name) {
  const index = routers.value.findIndex((v) => v.name === name);
  if (index <= 0) {
    return;
  }
  handleChange(routers.value[index - 1].name);
  setTimeout(() => {
    routers.value.splice(index, 1);
  }, 10);
}
watchEffect(() => {
  dfsArray(routeState.routerList, (item) => {
    if (item.path === route.path) {
      activeName.value = item.title;
      if (!routers.value.find((v) => v.path === item.path)) {
        routers.value.push({
          path: item.path,
          name: item.title,
          label: item.title,
          icon: item.icon,
          query: {},
        });
        if (routers.value.length === 1) {
          eventEmitter.emit("menu:update", item.path);
        }
      }
      return true;
    }
  });
});

function handleCommand(command) {
  const curPath = route.path;
  const index = routers.value.findIndex((v) => v.path === curPath);
  if (index === -1 && command !== "open") {
    return;
  }
  switch (command) {
    case "close":
      const r =
        index - 1 < 0 ? routers.value[index + 1] : routers.value[index - 1];
      router.replace({
        path: r.path,
        query: r.query || {},
      });
      // 放入宏任务执行 防止菜单无法更新
      setTimeout(() => {
        eventEmitter.emit("menu:update", r.path);
        routers.value.splice(index, 1);
      });
      break;
    case "closeLeft":
      routers.value.splice(0, index);
      break;
    case "closeRight":
      routers.value.splice(index + 1);
      break;
    case "closeOther":
      routers.value = [routers.value[index]];
      break;
    case "closeAll":
      const first = routers.value[0];
      router.replace({
        path: first.path,
        query: first.query || {},
      });
      setTimeout(() => {
        eventEmitter.emit("menu:update", first.path);
        routers.value = [first];
      });
      break;
    case "open":
      window.open(window.location.href);
      break;
  }
}
</script>

<style scoped>
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* padding-right: 15px; */
}
.nav-header .el-tabs {
  flex: 1;
}
.nav-header .actions {
  background-color: var(--bg-primary);
  height: 100%;
  display: flex;
  align-items: center;
  border: 1px solid var(--border-color);
}
.actions .action_item {
  height: 100%;
  padding: 0 5px;
}
.actions .action_item:hover {
  background: var(--bg-secondary);
}
.el-tabs {
  --el-tabs-header-height: 35px;
  padding-top: 5px;
}
.el-tabs :deep(.el-tabs__header.is-top) {
  margin-bottom: 0;
}
.el-tabs :deep(.el-tabs__content) {
  padding: 0;
}

.el-tabs :deep(.el-tabs__header) {
  --el-fill-color-light: transparent;
}
html.light .el-tabs :deep(.el-tabs__item.is-active) {
  --tabs-bg: var(--el-color-primary-light-9);
}
html.dark .el-tabs :deep(.el-tabs__item.is-active) {
  --tabs-bg: var(--bg-secondary);
}
.el-tabs :deep(.el-tabs__item.is-active) {
  background: var(--tabs-bg);
}

.google-tabs.el-tabs :deep(.el-tabs__nav) {
  --tailSize: 15px;
  padding-left: var(--tailSize);
}
.google-tabs.el-tabs :deep(.el-tabs__item) {
  border-radius: 10px 10px 0 0;
  position: relative;
  border: none;
  transition: background 0.3s ease-in-out;
}
.google-tabs.el-tabs :deep(.el-tabs__item.is-active)::before,
.google-tabs.el-tabs :deep(.el-tabs__item.is-active)::after {
  content: "";
  position: absolute;
  height: var(--tailSize);
  width: var(--tailSize);
  bottom: 0;
}
.google-tabs.el-tabs :deep(.el-tabs__item.is-active)::before {
  /* TODO: 暗色模式的颜色? */
  background: radial-gradient(
    circle at 0 0,
    transparent var(--tailSize),
    var(--tabs-bg) var(--tailSize)
  );
  left: calc(var(--tailSize) * -1);
}
.google-tabs.el-tabs :deep(.el-tabs__item.is-active)::after {
  background: radial-gradient(
    circle at var(--tailSize) 0,
    transparent var(--tailSize),
    var(--tabs-bg) var(--tailSize)
  );
  right: calc(var(--tailSize) * -1);
}
</style>
